<?php
/**
 * 保存模块配置
 * @param string $app 对应APP  $new_config 修正配置内容
 */
function save_config($app = NULL, $new_config = array()){
    if($app){
        $file = APP_PATH.'/'.$app.'/config.php';
    }else{
        $file = CONFIG_PATH.'config.php';
    }
    if(!file_exists($file)){
        throw new \Exception("APP Config '{$name}' not found", 500);
    }
    if( is_file($file) ) {
        $config = require($file);
        $config = array_merge($config, $new_config);
    }else{
        $config = $new_config;
    }
    $content = var_export($config, true);
    $content = str_replace("_PATH' => '" . addslashes(ROOT_PATH), "_PATH' => ROOT_PATH . '", $content);

    if( file_put_contents($file, "<?php \r\nreturn " . $content . ';' ) ) {
        return true;
    }
    return false;
}

/**
 * 认证查询
 * @return string  字符串
 */
function dev(){
    //return \framework\ext\Util::cpDecode('2fadVMwbhHc5Bkdjp3/09B7So2AQhtbk85jNkyLKb7TarbXNvgmXchHiU81Ruazz7nHcDNpuXuOSQ6P6Zg','siteplus');
    return 'http://cp.ilinzhou.cn';
}


//获取客户端IP
function get_client_ip(){
    return \framework\ext\Util::getIp();
}

//浏览器友好的变量输出
function dump($var, $exit=false){
    $output = print_r($var, true);
    $output = "<pre>" . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
    echo $output;
    if($exit) exit();
}

//获取微秒时间，常用于计算程序的运行时间
function utime(){
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

/**
 * 表单处理接口
 * @param  array  $str 要数据数的数据 $delete_value  删除无用数组 $function 回调函数
 * @return array        处理后的数据
 */
function form($str = null, $delete_value = array(), $function = '') {
    if(empty($str))return;
    $str = trim($str);
    list($method,$name) = explode('.',$str,2);
    $method = strtolower($method);
    switch ($method) {
        case 'get':
            $type = $_GET;
            break;
        case 'post':
            $type = $_POST;
            break;
        case 'session':
            $type = $_SESSION;
            break;
        case 'request':
            $type = $_REQUEST;
            break;
        case 'cookie':
            $type = $_COOKIE;
            break;
        default:
            return ;
    }
    if(empty($name)){
        $request = $type;
    }else{
        switch ($method) {
            case 'get':
                $request = urldecode($type[$name]);
                break;
            default:
                $request = $type[$name];
                break;
        }
    }
    $request = filter_string($request,$delete_value);
    if(!empty($name) && !empty($function)){
        $request = call_user_func($function,$request);
    }
    return $request;
}
/**
 * 过滤数据
 * @param  array  $form_array 需要过滤的数组 $delete_value  删除无用数组
 * @return array        过滤后的数据
 */
function filter_string($form_array,$delete_value = array()){
    if($form_array===NULL){
        return false;
    }
    if (is_array($form_array)){
        $default_delete = array('action','button','submit');
        $clear_array = array_merge($default_delete,$delete_value);
        foreach ($form_array as $key => $value){
            if(!in_array($key,$clear_array)){
                $data[$key] = filter_string($value);
            }
        }
        return $data;
    }else{
        return htmlspecialchars(trim($form_array),ENT_QUOTES, 'UTF-8');
    }
}
/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 调试运行时间和占用内存
 * @return string   微秒
 */
function debug($flag='system', $end = false){
    static $arr =array();
    if( !$end ){
        $arr[$flag] = microtime(true); 
    } else if( $end && isset($arr[$flag]) ) {
        echo  '<p>' . $flag . ': runtime:' . round( (microtime(true) - $arr[$flag]), 6)
             . '    memory_usage:' . memory_get_usage()/1000 . 'KB</p>'; 
    }
}

/**
 * 获取文件或文件大小
 * @param string $directoty 路径
 * @return int
 */
function dir_size($directoty){
    $dir_size = 0;
    if ($dir_handle = @opendir($directoty)) {
        while ($filename = readdir($dir_handle)) {
            $subFile = $directoty . DIRECTORY_SEPARATOR . $filename;
            if ($filename == '.' || $filename == '..') {
                continue;
            } elseif (is_dir($subFile)) {
                $dir_size += dir_size($subFile);
            } elseif (is_file($subFile)) {
                $dir_size += filesize($subFile);
            }
        }
        closedir($dir_handle);
    }
    return ($dir_size);
}

/**
 * 随机数
 * @param  string  $length 字符长度 $mode 随机方式
 * @return string  字符串
 */
function random_str($length = 6, $mode = 0){
    switch ($mode) {
        case '1':
            $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';
            break;
        case '2':
            $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-=[]\',./';
            break;
        case '3':
            $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ<>?:"|{}_+';
            break;
        case '4':
            $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        default:
            $str = '1234567890';
            break;       
    }
    $result = '';
    $l = strlen($str) - 1;
    $num = 0;
    for ($i = 0; $i < $length; $i++) {
        $num = rand(0, $l);
        $a = $str[$num];
        $result = $result . $a;
    }
    return $result;
}
/**
 * 生成唯一字符串(数字)
 * @return string  字符串
 */
function unique_str(){
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0,8);
}